#include "private_telnet_func.h"
#include "FSMC_SRAM.h"
#include "FreeRTOS_CLI.h"
#include "cli_static_resources.h"
#include "lwip/sockets.h"
char *rxbuf = (char *)TELNET_RXBUF_POOL;
struct user_info accounts[] = {
    {"admin", "admin"}};

static const uint8_t IAC_WILL_ECHO[] = {255, 251, 1}; /* 将关闭本地回显 */
static const uint8_t IAC_WONT_ECHO[] = {255, 252, 1}; /* 恢复本地回显   */
static const uint8_t IAC_WILL_SGA[] = {255, 251, 3};  /* Suppress Go-Ahead */

int cli_session_task(int sock)
{
  //   char rxbuf[128];
  char username[MAX_USER_LEN];
  char password[MAX_PASS_LEN];
  login_state_t state = ST_LOGIN_NAME;
  int fail_cnt = 0;
  size_t idx = 0; /* 当前输入索引 */

  /* ① 发送 telnet 协商 + 欢迎 */
  send(sock, IAC_WILL_SGA, 3, 0);
  send(sock, IAC_WILL_ECHO, 3, 0); /* 我们先关回显 */
  send(sock, "\r\nLinux 5.10.0-tiny (none) (ttyS0)\r\n\r\n", 42, 0);
  send(sock, "login: ", 7, 0);

  while (1)
  {
    int len = recv(sock, rxbuf, sizeof(rxbuf) - 1, 0);
    if (len <= 0)
      return -1;
    rxbuf[len] = 0;

    /* 逐字节处理，支持退格 */
    for (int i = 0; i < len; ++i)
    {
      uint8_t c = rxbuf[i];
      if (c == '\r' || c == '\n')
      { /* 回车 → 校验阶段 */
        if (state == ST_LOGIN_NAME)
        {
          username[idx] = 0;
          state = ST_LOGIN_PASS;
          idx = 0;
          /* 关闭回显，显示 * */
          send(sock, IAC_WONT_ECHO, 3, 0);
          send(sock, "\r\nPassword: ", 12, 0);
          continue;
        }
        if (state == ST_LOGIN_PASS)
        {
          password[idx] = 0;
          /* 验证账号密码 */
          int ok = 0;
          for (unsigned u = 0; u < sizeof(accounts) / sizeof(accounts[0]); ++u)
          {
            if (strcmp(username, accounts[u].user) == 0 &&
                strcmp(password, accounts[u].pass) == 0)
            {
              ok = 1;
              break;
            }
          }
          if (ok)
          {
            /* 成功：打开回显，发 motd，进 CLI */
            send(sock, IAC_WILL_ECHO, 3, 0);
            send(sock, "\r\n", 2, 0);
            send(sock,
                 "Welcome to FreeRTOS-Linux!\r\n"
                 " * Documentation:  https://www.kernel.org\r\n"
                 " * Support:        https://bbs.csdn.net\r\n\r\n",
                 120, 0);
            state = ST_NORMAL;
            send(sock, "[root@freertos ~]# ", 19, 0);
            idx = 0;
            continue;
          }
          /* 失败计数 */
          fail_cnt++;
          if (fail_cnt >= MAX_TRY)
          {
            send(sock, "\r\nLogin incorrect\r\n", 19, 0);
            return -1;
          }
          send(sock, "\r\nLogin incorrect\r\n", 19, 0);
          /* 重新开始 */
          state = ST_LOGIN_NAME;
          idx = 0;
          send(sock, "login: ", 7, 0);
          continue;
        }
      }
      else if (c == 127 || c == '\b')
      { /* 退格 */
        if (idx > 0)
        {
          --idx;
          if (state == ST_LOGIN_PASS)
            send(sock, "\b \b", 3, 0); /* 把 * 抹掉 */
          else
            send(sock, "\b \b", 3, 0); /* 用户名也抹 */
        }
        continue;
      }
      else if (idx < (state == ST_LOGIN_NAME ? MAX_USER_LEN : MAX_PASS_LEN) - 1)
      {
        if (state == ST_LOGIN_PASS)
          send(sock, "*", 1, 0); /* 密码回显 * */
        else
          send(sock, &c, 1, 0); /* 用户名正常回显 */
        /* 存进 buffer */
        if (state == ST_LOGIN_NAME)
          username[idx++] = c;
        else
          password[idx++] = c;
      }
    } /* for each char */

    /* 如果已登录，把整行交给 CLI（同上一节） */
    if (state == ST_NORMAL && idx > 0 && (rxbuf[len - 1] == '\n' || rxbuf[len - 1] == '\r'))
    {
      rxbuf[idx] = 0;
      //      char txbuf[configCOMMAND_INT_MAX_OUTPUT_SIZE];
      BaseType_t xMore;
      do
      {
        xMore = FreeRTOS_CLIProcessCommand(rxbuf, cOutputBuffer, sizeof(cOutputBuffer));
        send(sock, cOutputBuffer, strlen(cOutputBuffer), 0);
      } while (xMore != pdFALSE);
      send(sock, "[root@freertos ~]# ", 19, 0);
      idx = 0;
    }
  } /* while(1) */

  //disconnect:
  //  close(sock);
  //  vTaskDelete(NULL);
}